package com.ycxh.controller;

import com.ycxh.util.ErrorMessageEnum;
import com.ycxh.util.ViewResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    /**
     * 登陆
     */
    @PostMapping("/login")
    public String login(String username, String password, HttpSession session, HttpServletResponse response) throws Exception {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            response.setContentType("text/javascript; charset=utf-8");
            response.getWriter().write(ViewResult.newInstance().code(ErrorMessageEnum.失败.getCode())
                    .msg("用户名或者密码缺失").json());
            return null;
        }
        if (!"admin".equals(username) || !"admin".equals(password)) {
            response.setContentType("text/javascript; charset=utf-8");
            response.getWriter().write(ViewResult.newInstance().code(ErrorMessageEnum.失败.getCode())
                    .msg("用户名或者密码不正确").json());
            return null;
        }
        session.setAttribute("user", "admin");
        // 跳转到首页 工作台
        return "redirect:/nav";
    }

    /**
     * 登陆
     * ajax请求不支持重定向
     * https://blog.csdn.net/qq_33949023/article/details/111768699
     * https://blog.csdn.net/growing1224/article/details/120127291
     */
    @PostMapping("/loginAjax")
    public String loginAjax(String username, String password, HttpSession session, HttpServletResponse response) throws Exception {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            response.setContentType("text/javascript; charset=utf-8");
            response.getWriter().write(ViewResult.newInstance().code(ErrorMessageEnum.失败.getCode())
                    .msg("用户名或者密码缺失").json());
            return null;
        }
        if (!"admin".equals(username) || !"admin".equals(password)) {
            response.setContentType("text/javascript; charset=utf-8");
            response.getWriter().write(ViewResult.newInstance().code(ErrorMessageEnum.失败.getCode())
                    .msg("用户名或者密码不正确").json());
            return null;
        }
        session.setAttribute("user", "admin");
        // 跳转到首页
        // return "redirect:/index";
        response.getWriter().write(ViewResult.newInstance().code(ErrorMessageEnum.成功.getCode())
                .msg(ErrorMessageEnum.成功.getMsg()).json());
        return null;
    }

}
